
// Main header
#include "../Main.h"

//My header
#include "Panel.h"

// Fridge headers
#include "../Controller/Controller_Main.h"
#include "../MathsHelper.h"
#include "../TextureManager.h"

static const u_int uPANEL_BORDER_COLOUR = 0xAAAAAAFF;
static const u_int uPANEL_THIN_BORDER_COLOUR = 0x999999FF;

Panel::Panel( Widget* pxParent ) : Widget( pxParent )
{
	m_xImage = INVALID_STRING_HASH;
	m_uColour = 0xFFFFFFFF;
	m_fBorderWidth = 2.0f;
	m_bBorder = false;
}

Panel::~Panel()
{

}

void Panel::SetImage( const StringHash xHash )
{
	m_xImage = xHash;
	m_uColour = 0xFFFFFFFF;
}

void Panel::SetColour ( const u_int uColour )
{
	m_uColour = uColour;
	m_xImage = INVALID_STRING_HASH;
}

bool Panel::CanHaveChildren( ) const
{
	return true;
}

void Panel::Render()
{
	if( !m_bVisible )
	{
		return;
	}

	if( m_xImage != INVALID_STRING_HASH )
	{
		TextureManager* pxTextureManager = Controller_Main::GetTextureManager();
		
		if( pxTextureManager )
		{
			int iTextureID = pxTextureManager->GetTextureID( m_xImage );
			
			glColor4f( 1.0f, 1.0f, 1.0f, 1.0f );
			glBindTexture( GL_TEXTURE_2D, iTextureID );
		}
	}
	else
	{
		glBindTexture( GL_TEXTURE_2D, INVALID_TEXTURE_ID );
		
		u_int uSwapped = MathsHelper::RGBAtoABGR( m_uColour );

		glColor4ubv( reinterpret_cast<GLubyte*>( &uSwapped ) );
	}

	glEnable( GL_LINE_SMOOTH );
	glLineWidth( m_fBorderWidth );

	glBegin( GL_QUADS );

	glTexCoord2f( 0.0f, 0.0f );
	glVertex2i( GetResizedX(), GetResizedY() );
	glTexCoord2f( 0.0f, 1.0f );
	glVertex2i( GetResizedX(), GetResizedY() + GetResizedHeight() );
	glTexCoord2f( 1.0f, 1.0f );
	glVertex2i( GetResizedX() + GetResizedWidth(), GetResizedY() + GetResizedHeight() );
	glTexCoord2f( 1.0f, 0.0f );
	glVertex2i( GetResizedX() + GetResizedWidth(), GetResizedY() );

	glEnd();

	if( m_bBorder )
	{
		const float fPositionX = static_cast< float >( GetResizedX() );
		const float fPositionY = static_cast< float >( GetResizedY() );
		const float fWidth = static_cast< float >( GetResizedWidth() );
		const float fHeight = static_cast< float >( GetResizedHeight() );

		glBindTexture( GL_TEXTURE_2D, INVALID_TEXTURE_ID );

		u_int uSwapped = MathsHelper::RGBAtoABGR( m_fBorderWidth > 1.5f ? uPANEL_BORDER_COLOUR : uPANEL_THIN_BORDER_COLOUR );

		glColor4ubv( reinterpret_cast<GLubyte*>( &uSwapped ) );

	    glBegin( GL_LINE_LOOP );

	    // Top
	    // glVertex2f( fPositionX, fPositionY );
	    glVertex2f( fPositionX + fWidth, fPositionY );

        // Right
	    // glVertex2f( fPositionX + fWidth, fPositionY );
	    glVertex2f( fPositionX + fWidth, fPositionY + fHeight );

	    // Bottom
        // glVertex2f( fPositionX + fWidth , fPositionY + fHeight );
	    glVertex2f( fPositionX, fPositionY + fHeight );

	    // Left
        // glVertex2f( fPositionX, fPositionY + fHeight );
	    glVertex2f( fPositionX, fPositionY );


	    glEnd( );

	}

	Widget::Render();
}